package com.tarena.lbs.basic.web.repository.impl;


import com.tarena.lbs.basic.web.mapper.UserMapper;
import com.tarena.lbs.basic.web.mapper.UserTagsMapper;
import com.tarena.lbs.basic.web.repository.UserTagsRepository;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.dos.UserDO;
import com.tarena.lbs.pojo.basic.dos.UserTagsDO;
import com.tarena.lbs.pojo.basic.param.UserTagsParam;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class UserTagsRepositoryImpl implements UserTagsRepository {

    @Resource
    private UserTagsMapper userTagsMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(UserTagsParam param) {
        UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
        if (loginUser != null) {
            param.setUserId(loginUser.getId());
        }
        List<UserTagsDO> record = new ArrayList<>();
        for (String temp : param.getTagIds().split(",")) {
            UserTagsDO tempDo = new UserTagsDO();
            tempDo.setUserId(param.getUserId());
            tempDo.setTagId(Integer.valueOf(temp));
            record.add(tempDo);
        }
        userTagsMapper.deleteByUserId(param.getUserId());
        userTagsMapper.batchInsertTags(record);
        UserDO userDO = new UserDO();
        userDO.setStatus(1);
        userDO.setId(param.getUserId());
        userMapper.updateByPrimaryKeySelective(userDO);
    }

    @Override
    public List<UserTagsDO> selectByUserId(Integer id) {
        //适配登陆用户
        if (id == null) {
            UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
            if (loginUser != null) {
                id = loginUser.getId();
            }
        }
        return userTagsMapper.selectByUserId(id);
    }

}
